﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using Data.Api.Repositories;
using Data.Mappers;

namespace Data.Repositories
{
    public class ProductsRepository : Repository<Entity.Products.Product, Data.ModelDatabase.Product>, IProductsRepository
    {
        public ProductsRepository(Db.IDbShopConcreteContext context, IMapper<Entity.Products.Product, ModelDatabase.Product> mapper)
            : base(context, context.Products, mapper)
        { }

        public override void Update(Entity.Products.Product entity)
        {
            Data.ModelDatabase.Product product = dbSet.Find(entity.Id);
            product.Description = entity.Description;
            product.Name = entity.Name;
            product.Price = entity.Price;

            context.Context.Entry(product).State = System.Data.EntityState.Modified;
        }


        public override void Insert(Entity.Products.Product entity)
        {
            Data.ModelDatabase.Product product = new ModelDatabase.Product() { Description = entity.Description, Name = entity.Name, Price = entity.Price };
            product.Categories = new List<Data.ModelDatabase.Category>();

            foreach (var cat in entity.Categories)
                product.Categories.Add(context.Categories.Find(cat.Id));

            context.Context.Entry(product).State = System.Data.EntityState.Added;
        }


        public void UpdateCategories(Entity.Products.Product entity)
        {
            Data.ModelDatabase.Product product = dbSet.Find(entity.Id);
            product.Categories.Clear();

            foreach (var cat in entity.Categories)
                product.Categories.Add(context.Categories.Find(cat.Id));

            base.context.Context.Entry(product).State = System.Data.EntityState.Modified;
        }
    }
}
